import os
import uuid
from datetime import datetime
from turtle import pd

import pymysql
from flask import request, Flask, jsonify, Response, send_from_directory
from werkzeug.security import generate_password_hash, check_password_hash
from flask_cors import CORS

dataTime = datetime.now()
# 连接数据库
# db = pymysql.connect(host='连接数据库的ip地址',port='端口', user='用户名', password='密码', db='连接的数据库')
db = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='book_store')
print(db.port)
cursor = db.cursor()  # 指定数据库指针

#  启动后端
app = Flask(__name__)
CORS(app, resources=r'/*')  # 解决跨域问题

#注册账号
@app.route('/api/register', methods=["POST"])
def register():
    if request.method == 'POST':
        phone = request.json.get("phone")
        password = request.json.get("password")
        name = request.json.get("name")
        if not name or not phone or not password:
            return jsonify({'error': '手机号和密码不能为空！'}), 400
        try:
            # 密码加密
            # password = generate_password_hash(password)
            cursor.execute("insert into t_user(phone,password,dataTime,name) values(" + str(phone) + "," + str(password) + ",'" + dataTime.strftime('%Y-%m-%d') + "','" + name + "')")
            db.commit()
            return jsonify({
                'success': '注册成功!',
                'code': 200
           })
        except Exception as e:
            print("failed:", e)
            return jsonify({'error': e})

#  login登录操作,返回数据库查询到的密码并返回（已完成返回密码操作）
@app.route('/api/login', methods=["POST"])  # 使用POST请求
def login():
    phone = request.json.get("phone")
    pwd = request.json.get("pwd")

    # 验证输入不能为空
    if not phone or not pwd:
        return jsonify({'error': '手机号和密码不能为空！'}), 400
    try:
        # 发送数据库
        cursor.execute("select * from t_user where phone=" + str(phone))
        date = cursor.fetchone()  # 返回第一条查询信息
        token = str(uuid.uuid1())
        if not date:
            return jsonify({
                'code': 400,
                'error': '手机号不存在!'
            })
        userInfo = [
            {
                'id': date[0],
                'phone': date[1],
                'password': date[2],
                'dataTime': dataTime.strftime('%Y-%m-%d'),
                'token': token
            }
        ]

        if date[2] == pwd:
            return jsonify({
                'code': 200,
                'success': '登录成功!',
                'data': userInfo
            }), 200  # 号码查找到密码，返回密码
        else:
            return jsonify({
                'code': 400,
                'error': '密码错误!'
            })

    except Exception as e:
        return jsonify(
            {'error': '服务器异常'}
        ), 500


'''
这段代码价值1个亿
'''


@app.route('/login/update', methods=["POST"])  # 使用POST请求
def login_update():
    if request.method == 'POST':
        phone = request.form.get("phone")
        password = request.form.get("password")
        # 做异常测试
        try:
            if phone == '':
                return jsonify({
                    'error': '手机号不能为空!'
                }), 400
            cursor.execute("update t_user set password=" + str(password) + " where phone=" + str(phone))
            cursor.execute("commit;")
            return jsonify({
                'success': '修改成功!',
                'code': 200
            })
        except Exception as e:
            print("failed:", e)
            return '-1'  # 未完成修改操作，返回-1


# 获取表格中的数据
@app.route('/api/getData', methods=["GET"])
def getData():
    if request.method == 'GET':
        name = request.args.get("name")
        try:
            if name:
                cursor.execute("select * from t_user where name like '%" + name + "%'")
            else:
                cursor.execute("select * from t_user")
            date = cursor.fetchall()
            date = list(reversed(date))
            date = [
                {
                    'id': i[0],
                    'phone': i[1],
                    'dataTime': i[3].strftime("%Y-%m-%d"),
                    'name': i[4],
                    'address': i[5]
                } for i in date
            ]
            return jsonify({
                'code': 200,
                'data': date,
                'total': len(date)
            })
        except Exception as e:
            print("failed:", e)
            return jsonify({'error': e})


@app.route('/api/editTable', methods=["POST"])
def editTable():
    if request.method == 'POST':
        id = request.json.get("id")
        name = request.json.get("name")
        phone = request.json.get("phone")
        dataTime = request.json.get("dataTime")
        if name and phone and dataTime:
            try:
                cursor.execute("update t_user set name='" + name + "',phone='" + phone + "',dataTime='" + dataTime + "' where id=" + str(id))
                cursor.execute("commit;"),
                return jsonify({
                    'success': '修改成功!',
                    'code': 200
                })
            except Exception as e:
                print("failed:", e)
                return '-1'


# 删除
@app.route('/api/deleteTable', methods=["POST"])
def deleteTable():
    if request.method == 'POST':
        id = request.json.get("id")
        try:
            cursor.execute("delete from t_user where id=" + str(id))
            cursor.execute("commit;")
            return jsonify({
                'success': '删除成功!',
                'code': 200
            })
        except Exception as e:
            print("failed:", e)
            return '-1'


# 从数据库获取省市县的数据
@app.route('/api/getCity', methods=["GET"])
def getCity():
    if request.method == 'GET':
        try:
            # 先查询省
            cursor.execute("select * from province")
            # 在查询市
            cursor.execute("select * from city")
            # 在查询县
            cursor.execute("select * from county")
            # 然后组成树形结构返回给前端
            date = cursor.fetchall()
            date = [
                {
                    'id': i[0],
                    'name': i[1],
                    'parentId': i[3]
                } for i in date
            ]
            return jsonify({
                'code': 200,
                'data': date,
                'total': len(date)
            })
        except Exception as e:
            print("failed:", e)
            return jsonify({'error': e})


# 上传图片
@app.route('/api/upload', methods=["POST"])
def upload():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            return jsonify({
                'success': '上传成功!',
                'code': 200,
                'url': file.filenUrl
            })
        return jsonify({
            'error': '上传失败!'
        })


# 启动后端服务器
if __name__ == '__main__':
    app.run(host='192.168.162.124', port=8888)  # 启动后端服务器，定义接口，监听端口；0.0.0.0表示都可以访问的地址。
    db.close()

# '192.168.162.124' 怎么做代理
